package com.group.itms.routes.map;

import java.util.ArrayList;
import java.util.List;

import android.os.Looper;

public class OfflineMap {

	private OfflineMapView mMapView;

	private List<Layer> mLayers = new ArrayList<Layer>();
	private Projection mProjection;
	private PointD mMyLocation;
	private boolean mRedrawView = true;
	
	public Layer getLayer(int id) {
		Layer l = findLayer(id);
		if (l == null) {
			l = new Layer();
			l.setId(id);
			l.setMap(this);
			l.setProjection(mProjection);
			l.setVisible(true);
		}
		return l;
	}
	
	void setMapView(OfflineMapView mapView) {
		mMapView = mapView;
	}
	
	OfflineMapView getMapView() {
		return mMapView;
	}
	
	public void setMyLocation(PointD loc) {
		mMyLocation = loc;
	}

	public PointD getMyLocation() {
		return mMyLocation;
	}
	
	public void setRedrawView(boolean update) {
		mRedrawView = update;
	}
	
	public void redrawView() {
		if (mRedrawView) {
			doUpdateMapView();
		}
	}
	
	public void doUpdateMapView() {
		if (Looper.myLooper() == Looper.getMainLooper()) {
			mMapView.invalidate();
		} else {
			mMapView.postInvalidate();
		}
	}

	public Projection getProjection() {
		return mProjection;
	}

	public void setProjection(Projection projection) {
		mProjection = projection;
	}

	public List<Layer> getLayers() {
		return mLayers;
	}
	
	public void addLayers(List<Layer> layers) {
		setRedrawView(false);
		for (Layer l : layers) {
			addLayer(l);
		}
		setRedrawView(true);
		redrawView();
	}
	
	public void addLayer(Layer layer) {
		mLayers.add(layer);
		layer.setMap(this);
		layer.setProjection(mProjection);
		redrawView();
	}

	public void removeLayer(Layer layer) {
		if (mLayers.remove(layer)) {
			layer.setMap(null);
		}
	}
	
	public Layer findLayer(int id) {
		for (Layer l : mLayers) {
			if (l.getId() == id) {
				return l;
			}
		}
		return null;
	}
}